<template>
  <div class="page-wrapper">
    <!-- 页面头部 -->
    <div class="page-header">
      <span class="text-primary font-bold">字典管理</span>
      <el-button type="primary" @click="handleAdd">新增字典</el-button>
    </div>
    <!-- 页面内容 -->
    <div class="page-content">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="字典名称">
          <el-input v-model="searchForm.name" placeholder="请输入字典名称" clearable />
        </el-form-item>
        <el-form-item label="字典类型">
          <el-input v-model="searchForm.type" placeholder="请输入字典类型" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <div class="table-wrapper">
        <!-- 字典列表 -->
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="name" label="字典名称" />
          <el-table-column prop="type" label="字典类型" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'info'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="success" link @click="handleViewData(row)">字典数据</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增字典' : '编辑字典'"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="type">
          <el-input v-model="form.type" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 字典数据对话框 -->
    <el-dialog v-model="dataDialogVisible" title="字典数据" width="800px">
      <div class="dict-data-header">
        <div class="dict-info">
          <span>字典名称：{{ currentDict?.name }}</span>
          <span>字典类型：{{ currentDict?.type }}</span>
        </div>
        <el-button type="primary" @click="handleAddData">新增字典数据</el-button>
      </div>

      <!-- 字典数据列表 -->
      <el-table :data="dictDataList" border v-loading="dataLoading" style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="label" label="数据标签" />
        <el-table-column prop="value" label="数据值" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditData(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDeleteData(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="dictDataPage.currentPage"
          v-model:page-size="dictDataPage.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="dictDataPage.total"
          @size-change="handleDictDataSizeChange"
          @current-change="handleDictDataCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-dialog>

    <!-- 字典数据编辑对话框 -->
    <el-dialog
      v-model="dataFormVisible"
      :title="dataFormType === 'add' ? '新增字典数据' : '编辑字典数据'"
      width="500px"
    >
      <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px">
        <el-form-item label="数据标签" prop="label">
          <el-input v-model="dataForm.label" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据值" prop="value">
          <el-input v-model="dataForm.value" placeholder="请输入数据值" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="dataForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dataFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDataSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listDict,
  addDict,
  updateDict,
  deleteDict,
  listDictData,
  addDictData,
  updateDictData,
  deleteDictData,
} from '@/api/system/dict'
import type { DictType, DictData } from '@/types/system/dict'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: undefined as undefined | number,
})

// 表格数据
const tableData = ref<DictType[]>([])
const loading = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载字典类型列表
const loadDictList = async () => {
  loading.value = true
  try {
    const res = await listDict({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取字典列表失败:', error)
    ElMessage.error('获取字典列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadDictList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.type = ''
  searchForm.status = undefined
  handleSearch()
}

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive<DictType>({
  name: '',
  type: '',
  status: 1,
  remark: '',
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
  type: [{ required: true, message: '请输入字典类型', trigger: 'blur' }],
}

// 新增字典
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  form.name = ''
  form.type = ''
  form.status = 1
  form.remark = ''
}

// 编辑字典
const handleEdit = (row: DictType) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(form, row)
}

// 删除字典
const handleDelete = async (row: DictType) => {
  try {
    await ElMessageBox.confirm('确认删除该字典吗？', '提示', {
      type: 'warning',
    })
    await deleteDict(row.id!)
    ElMessage.success('删除成功')
    loadDictList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交字典表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addDict(form)
        } else {
          await updateDict(form)
        }
        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
        dialogVisible.value = false
        loadDictList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 字典数据相关
const dataDialogVisible = ref(false)
const currentDict = ref<DictType | null>(null)
const dictDataList = ref<DictData[]>([])
const dataLoading = ref(false)

// 字典数据分页参数
const dictDataPage = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 查看字典数据
const handleViewData = async (row: DictType) => {
  currentDict.value = row
  dataDialogVisible.value = true
  // 重置分页参数
  dictDataPage.currentPage = 1
  dictDataPage.pageSize = 10
  await loadDictDataList(row.type)
}

// 加载字典数据列表
const loadDictDataList = async (dictType: string) => {
  dataLoading.value = true
  try {
    const res = await listDictData({
      pageNum: dictDataPage.currentPage,
      pageSize: dictDataPage.pageSize,
      dictType,
    })
    dictDataList.value = res.data.list
    dictDataPage.total = res.data.total
  } catch (error) {
    console.error('获取字典数据失败:', error)
    ElMessage.error('获取字典数据失败')
  } finally {
    dataLoading.value = false
  }
}

// 字典数据分页处理
const handleDictDataSizeChange = (val: number) => {
  dictDataPage.pageSize = val
  if (currentDict.value) {
    loadDictDataList(currentDict.value.type)
  }
}

const handleDictDataCurrentChange = (val: number) => {
  dictDataPage.currentPage = val
  if (currentDict.value) {
    loadDictDataList(currentDict.value.type)
  }
}

// 字典数据表单
const dataFormVisible = ref(false)
const dataFormType = ref<'add' | 'edit'>('add')
const dataFormRef = ref<FormInstance>()
const dataForm = reactive<DictData>({
  dictType: '',
  label: '',
  value: '',
  sort: 0,
  status: 1,
})

// 字典数据校验规则
const dataRules = {
  label: [{ required: true, message: '请输入数据标签', trigger: 'blur' }],
  value: [{ required: true, message: '请输入数据值', trigger: 'blur' }],
}

// 新增字典数据
const handleAddData = () => {
  if (!currentDict.value) return
  dataFormType.value = 'add'
  dataFormVisible.value = true
  dataForm.dictType = currentDict.value.type
  dataForm.label = ''
  dataForm.value = ''
  dataForm.sort = 0
  dataForm.status = 1
}

// 编辑字典数据
const handleEditData = (row: DictData) => {
  dataFormType.value = 'edit'
  dataFormVisible.value = true
  Object.assign(dataForm, row)
}

// 删除字典数据
const handleDeleteData = async (row: DictData) => {
  try {
    await ElMessageBox.confirm('确认删除该字典数据吗？', '提示', {
      type: 'warning',
    })
    await deleteDictData(row.id!)
    ElMessage.success('删除成功')
    if (currentDict.value) {
      // 如果当前页只有一条数据，删除后跳转到上一页
      if (dictDataList.value.length === 1 && dictDataPage.currentPage > 1) {
        dictDataPage.currentPage--
      }
      loadDictDataList(currentDict.value.type)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交字典数据表单
const handleDataSubmit = async () => {
  if (!dataFormRef.value) return
  await dataFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dataFormType.value === 'add') {
          await addDictData(dataForm)
        } else {
          await updateDictData(dataForm)
        }
        ElMessage.success(dataFormType.value === 'add' ? '新增成功' : '修改成功')
        dataFormVisible.value = false
        if (currentDict.value) {
          // 重置到第一页
          dictDataPage.currentPage = 1
          loadDictDataList(currentDict.value.type)
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadDictList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadDictList()
}

// 初始化加载
onMounted(() => {
  loadDictList()
})
</script>

<style scoped>
.dict-data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dict-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}
</style>
